package org.Lin.service;

import org.Lin.dao.UserDAO;
import org.Lin.model.User;
import org.Lin.util.HashUtil;
import org.Lin.util.LogUtil;

import java.sql.SQLException;

public class UserService {

    private final UserDAO userDAO = new UserDAO();

    public boolean registerUser(int userID, String name, String password, String email) {
        try {
            if (userDAO.findByUserID(userID) != null) {
                return false; // 用户已存在
            }
            String hashedPassword = HashUtil.hashPassword(password);
            User user = new User();
            user.setUserID(userID);
            user.setName(name);
            user.setPassword(hashedPassword);
            user.setEmail(email);
            user.setAccountStatus("正常");
            userDAO.insert(user);

            LogUtil.logOperation("User", "register", "用户注册: " + userID);
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    public User loginUser(int userID, String password) {
        try {
            User user = userDAO.findByUserID(userID);
            if (user != null && user.getPassword().equals(HashUtil.hashPassword(password))) {
                LogUtil.logOperation("User", "login", "用户登录: " + userID);
                return user;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void updateLastLogin(int userID) {
        try {
            User user = userDAO.findByUserID(userID);
            if (user != null) {
                user.setLastLogin(java.time.LocalDateTime.now());
                userDAO.update(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
